package th.retrofit.lib;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/subsets/
 * 给你一个整数数组 nums ，数组中的元素 互不相同 。返回该数组所有可能的子集（幂集）。
 * 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
 */
final class Solution78 {

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> set = new ArrayList<>(nums.length);
        dfs(results, set, nums, 0);
        return results;
    }

    private void dfs(List<List<Integer>> results, List<Integer> set, int[] nums, int index) {
        if (index == nums.length) {
            results.add(new ArrayList<>(set));
            return;
        }
        set.add(nums[index]);
        dfs(results, set, nums, index + 1);
        set.remove(set.size() - 1);
        dfs(results,set, nums, index + 1);
    }

    public List<List<Integer>> subsets1(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> set = new ArrayList<>(nums.length);
        backtrack(results, set, nums, 0);
        return results;
    }

    private void backtrack(List<List<Integer>> results, List<Integer> set, int[] nums, int index) {
        results.add(new ArrayList<>(set));
        for (int i = index; i < nums.length; i++) {
            set.add(nums[i]);
            backtrack(results, set, nums, i + 1);
            set.remove(set.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 4};
        List<List<Integer>> results = new Solution78().subsets1(nums);
        for (List<Integer> sub : results) {
            for (Integer i : sub) {
                System.out.print(i);
                System.out.print(",");
            }
            System.out.println();
        }
    }

}
